package com.example.ldachu.testdownload.http.util;

/**
 * @author zxKueen on 2017-12-26 10:36
 * Email: 4994766@qq.com
 */

import com.example.ldachu.testdownload.http.RetrofitFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * 使用retrofit进行下载
 */
public class DownloadUtil {
    private static volatile DownloadUtil instance;

    private DownloadUtil() {
    }

    public static DownloadUtil getInstance() {
        if (instance == null) {
            synchronized (DownloadUtil.class) {
                if (instance == null) {
                    instance = new DownloadUtil();
                }
            }
        }
        return instance;
    }


    public void download(final String url, final String dir, final OnDownloadListener listener){
        RetrofitFactory.getInstance().getService()
                .download(url)
                .compose(RxUtil.schedulers())
                .subscribe(new Observer<ResponseBody>(){
                    @Override
                    public void onSubscribe(Disposable d) {


                    }

                    @Override
                    public void onNext(ResponseBody response) {
                        InputStream is = null;
                        FileOutputStream fos = null;
                        File file = null;
                        //获取链接的文件名
                        String fileName = url.substring(url.lastIndexOf("/"));
                        byte[] buffer = new byte[1024];
                        int len = -1;

                        is = response.byteStream();
                        //文件的大小
                        long total = response.contentLength();
                        file = new File(dir,fileName);

                        //判断当前文件夹是否存在
                        if(file.getParentFile().exists()){
                            //存在，遍历并删除文件
                            File[] files = file.getParentFile().listFiles();
                            if(files!=null && files.length>0){
                                for(File f : files){
                                    f.delete();
                                }
                            }
                        }else{
                            //不存在创建文件夹
                            file.getParentFile().mkdirs();
                        }

                        try {
                            fos = new FileOutputStream(file);
                            //用于计算进度
                            long sum = 0;
                            while ((len = is.read(buffer))!=-1){
                                fos.write(buffer,0,len);
                                sum += len;
                                int progress = (int)(sum*1.0f/total*100);
                                //下载中
                                listener.onLoadding(progress);

                            }
                            //可以不调用
                            fos.flush();
                            //下载完成
                            listener.onSuccess();


                        }catch (IOException e) {
                            e.printStackTrace();
                            if(file!=null){
                                file.delete();
                            }
                            listener.onFailed();
                        }finally {
                            CloseUtils.closeIO(is);
                            CloseUtils.closeIO(fos);
                        }


                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.onFailed();
                    }

                    @Override
                    public void onComplete() {
                        listener.onSuccess();
                    }
                });
    }

    /**
     * 下载的接口回调
     */
    public abstract class OnDownloadListener{
        /**
         * 下载成功
         */
        public void onSuccess(){}

        /**
         * 正在下载
         */
        public void onLoadding(int progress){}

        /**
         * 下载失败
         */
        public void onFailed(){}


    }

}
